package org.eenie.learn.seedquartz.controllers;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;
import org.eenie.learn.seedquartz.config.Config;
import org.eenie.learn.seedquartz.model.OrderModel;
import org.eenie.learn.seedquartz.model.RemoteSeat;
import org.eenie.learn.seedquartz.model.ShipTicketModel;
import org.eenie.learn.seedquartz.utils.DealStrSub;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TicketController {
    private static final String AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) MicroMessenger/2.3.26(0x12031a10) MacWechat NetType/WIFI WindowsWechat";
    @Autowired
    TicketApi mTicketApi;
    Map<String, String> header = new HashMap<>();

    public TicketController() {
        header.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) MicroMessenger/2.3.26(0x12031a10) MacWechat NetType/WIFI WindowsWechat");
        header.put("Cookie", "zhhxuinfo=" + Config.zhhxuinfo + "; ASP.NET_SessionId=" + Config.sessionId);
    }


    public void refresh() {
        header.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) MicroMessenger/2.3.26(0x12031a10) MacWechat NetType/WIFI WindowsWechat");
        header.put("Cookie", "zhhxuinfo=" + Config.zhhxuinfo + "; ASP.NET_SessionId=" + Config.sessionId);
    }




    public Observable<ResponseBody> setTargetTicket() {
        return mTicketApi.setTargetTicket(header, "沈家门", "东极", "2019-10-02");
    }

    public Observable<List<RemoteSeat>> fetchTicketInfo(String busid, String ttype) {
        return mTicketApi.fetchTicketInfo(header, busid, ttype)
                .map(new Function<ResponseBody, List<RemoteSeat>>() {
                    @Override
                    public List<RemoteSeat> apply(ResponseBody body) throws Exception {
                        String content = DealStrSub.getSubUtilSimple(body.string(), "shippricelst=(.*?);");
                        return JSON.parseArray(content, RemoteSeat.class);

                    }
                });
    }


    public Observable<JSONObject> sendToWx(String title, String desc) {

        return Observable.just("")
                .flatMap(new Function<String, ObservableSource<JSONObject>>() {
                    @Override
                    public ObservableSource<JSONObject> apply(String key) throws Exception {
                        return mTicketApi.sendToWx(key, title, desc)
                                .map(new Function<ResponseBody, JSONObject>() {
                                    @Override
                                    public JSONObject apply(ResponseBody body) throws Exception {
                                        return JSON.parseObject(body.string());
                                    }
                                });
                    }
                });


    }

    public Observable<JSONObject> submit(List<OrderModel> orderModels) {
        return mTicketApi.submit(header, JSON.toJSONString(orderModels), 0, "")
                .map(new Function<ResponseBody, JSONObject>() {
                    @Override
                    public JSONObject apply(ResponseBody body) throws Exception {
                        return JSON.parseObject(body.string());
                    }
                });
    }

    public Observable<List<ShipTicketModel>> fetchTicketState() {
        return mTicketApi.fetchTicketState(header, "2019-10-02")
                .map(new Function<ResponseBody, List<ShipTicketModel>>() {
                    @Override
                    public List<ShipTicketModel> apply(ResponseBody body) throws Exception {
                        List<ShipTicketModel> ships = new ArrayList<>();
                        Document html = Jsoup.parse(body.string());
                        Elements els = html.select(".many_ships li");

                        if (!els.text().contains("无网售信息")) {
                            for (Element ele : els) {
                                ShipTicketModel model = new ShipTicketModel();
                                String content = ele.attr("onclick");
                                if (content.contains("selectship")) {
                                    String[] s = content.split("'");
                                    model.setBusid(s[1]);
                                    model.setTtype(s[3]);
                                    model.setActive(true);
                                }
                                Elements loc = ele.select(".always");
                                model.setStartLocation(loc.get(0).text());
                                model.setEndLocation(loc.get(1).text());
                                model.setCount(Integer.parseInt(ele.select(".fr.price").get(0).child(1).text().split(":")[1]));
                                model.setDate(ele.select(".fepar_time").text());
                                ships.add(model);
                            }
                        }
                        return ships;
                    }
                });
    }


}
